<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/18
 * Time: 10:35
 */

namespace app\admin\controller;

use app\admin\model\GoodsSpec as GoodsSpecModel;
use app\admin\model\GoodsModel as GoodsModelModel;
use app\admin\model\GoodsSpecItem as GoodsSpecItemModel;

class GoodsSpecController extends BaseController
{
    public function index()
    {
        $this->assign([
            'goodsSpecs' => GoodsSpecModel::with('item')->order(['id'=>'asc'])->paginate(15,false,['type'=>'page\Page']),
        ]);
        return $this->fetch();
    }

    public function add()
    {
        if($this->request->isGet()){
            $this->assign([
                'goodsModels' => GoodsModelModel::order(['id'=>'asc'])->select(),
            ]);
            return $this->fetch();
        }
        if($this->request->isPost()){
            $params = $this->request->param();
            if(empty($params['model_id'])){
                return ['error'=>1,'msg'=>'模型未定义'];
            }

            return (new GoodsSpecModel())->addEdi($params);
        }
        return ['error'=>9,'msg'=>'非法操作!'];
    }

    public function edi()
    {
        $params  = $this->request->param();
        if($this->request->isGet()){
            $goodsSpecItem = GoodsSpecItemModel::field('name')->where(['spec_id'=>$params['id']])->select();
            $specItems = '';
            foreach($goodsSpecItem as $k=>$v){
                $specItems .= $v->name.PHP_EOL;
            }
            $this->assign([
                'goodsModels' => GoodsModelModel::order(['id'=>'asc'])->select(),
                'goodsSpec' => GoodsSpecModel::find($params['id']),
                'specItems' => $specItems,
            ]);
            return $this->fetch();
        }
        if($this->request->isPost()){
            return (new GoodsSpecModel())->addEdi($params,true);
        }
        return ['error'=>9,'msg'=>'非法操作!'];
    }

    public function del()
    {
        $id = $this->request->param('id');
        GoodsSpecItemModel::where(['spec_id'=>$id])->delete();
        if(GoodsSpecModel::where(['id'=>$id])->delete()){
            return ['error'=>0,'msg'=>'删除成功!'];
        }else{
            return ['error'=>1,'msg'=>'删除失败!'];
        }
    }
}